package org.fluidripple.socket.inbound;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;
import org.fluidripple.socket.operation.ChannelOperation;
import org.fluidripple.socket.protocol.DeviceCollectModelProtocol;
import org.fluidripple.socket.protocol.DeviceSerializableProtocol;
import org.fluidripple.socket.protocol.DeviceStopCollectProtocol;
import org.fluidripple.socket.session.Session;
import org.fluidripple.socket.session.SessionManager;

import java.util.concurrent.TimeUnit;

/**
 * 事件处理器
 */
@Slf4j
@ChannelHandler.Sharable
public class ClientEventHandler extends AbstractInboundHandler {

    public static final String name = "client-event";

    /**
     * 连接事件
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws InterruptedException {
        log.info("设备建立连接");
        Session session = SessionManager.getSession(ctx);
        SessionManager.register(session);
//        DeviceStopCollectProtocol stopCollectProtocol = new DeviceStopCollectProtocol();
//        stopCollectProtocol.writer(ctx.channel());
//        TimeUnit.SECONDS.sleep(10);
//        DeviceSerializableProtocol protocol = new DeviceSerializableProtocol();
//        protocol.writer(ctx.channel());
        DeviceCollectModelProtocol modelProtocol = new DeviceCollectModelProtocol();
        modelProtocol.writer(ctx.channel());
        ctx.fireChannelActive();
    }

    /**
     * 读事件
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg){
        try {
            ctx.fireChannelRead(msg);
        }catch (Exception e){
            log.info("系统异常=>",e);
        }finally {
//            ByteBuf buf = (ByteBuf) msg;
//            if (buf.refCnt()>0){
//                buf.release(buf.refCnt());
//            }
        }
    }


    /**
     * 断开连接
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        if (!channel.isActive()){
            log.info("channel 不活跃了.....");
            ChannelOperation.closeChannel(channel,null);
            super.channelInactive(ctx);
        }else {
            Session session = SessionManager.getSession(channel);
            String deviceNo = session.getDeviceSerializable();
            String remoteAddressStr = session.getRemoteAddressStr();
            log.info("\uD83C\uDF3A 设备 {}，ip={} 触发了channel断开连接，但是这个channel依然是激活状态",deviceNo,remoteAddressStr);
        }
    }


    /**
     * 心跳事件
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        //心跳事件
        if (evt instanceof IdleStateEvent){
            IdleStateEvent event=(IdleStateEvent) evt;
            //服务器监听读写空闲事件
            if (event.state()== IdleState.ALL_IDLE){
                Channel channel = ctx.channel();
                Session session = SessionManager.getSession(channel);
                String deviceNo = session.getDeviceSerializable();
                String sessionId = session.getSessionId();
                log.info("=> 设备：{}，sessionId={}。当前channel读写事件超时.......关闭channel",deviceNo,sessionId);
                ChannelOperation.closeChannel(channel,null);
            }
        }
        super.userEventTriggered(ctx,evt);
    }

}
